<template>
  <el-dialog
    v-model="props.dialogVisible"
    :title="props.title"
    width="600px"
    top="3vh"
    :before-close="() => emit('close')"
  >
    <el-form
      ref="userEl"
      :model="state.formData"
      label-width="80px"
      :rules="formRules"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户昵称" prop="nickName">
            <el-input
              v-model="state.formData.nickName"
              placeholder="请输入用户昵称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="归属部门" prop="deptId">
            <el-tree-select
              v-model="state.formData.deptId"
              :data="state.deptTreeData"
              check-strictly
              :props="deptProps"
              :render-after-expand="false"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <!--新建用户的时候显示名称和密码输入框，否则不能修改-->
        <el-col :span="12" v-if="!state.formData.userId">
          <el-form-item label="账号" prop="userName">
            <el-input
              v-model="state.formData.userName"
              placeholder="请输入账号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="!state.formData.userId">
          <el-form-item label="用户密码" prop="password">
            <el-input
              type="password"
              show-password
              v-model="state.formData.password"
              placeholder="请输入用户密码"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input
              v-model="state.formData.phonenumber"
              placeholder="请输入手机号码"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="state.formData.email" placeholder="请输入邮箱" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户性别" prop="sex">
            <el-radio-group v-model="state.formData.sex">
              <el-radio label="0">男</el-radio>
              <el-radio label="1">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="state.formData.status">
              <el-radio label="0">正常</el-radio>
              <el-radio label="1">停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="角色" prop="roleIds">
            <el-select
              style="width: 100%"
              v-model="state.formData.roleIds"
              :multiple="true"
              :clearable="true"
              placeholder="请选择角色"
            >
              <el-option
                v-for="item in state.roleOptionData"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId"
                :disabled="item.status === 1"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input
              type="textarea"
              :rows="3"
              v-model="state.formData.remark"
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="() => emit('close')">取消</el-button>
        <el-button type="primary" @click="onConfirm"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {
  defineExpose,
  defineProps,
  defineEmits,
  reactive,
  onMounted,
  ref,
} from 'vue'
import { ElMessage } from 'element-plus'
import { listDept } from '@/api/dept/index'
import { addUser, getUser, updateUser } from '@/api/user/index'

const userEl = ref()
const emit = defineEmits(['close'])
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: '',
  },
  isAdd: {
    type: Boolean,
    default: false,
  },
})
const deptProps = {
  value: 'deptId',
  label: 'deptName',
  children: 'children',
}
// 校验数据
const formRules = reactive({
  userName: [
    { required: true, message: '用户名称不能为空', trigger: 'blur' },
    {
      min: 2,
      max: 20,
      message: '用户名称长度必须介于 2 和 20 之间',
      trigger: 'blur',
    },
  ],
  nickName: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }],
  password: [
    { required: true, message: '用户密码不能为空', trigger: 'blur' },
    {
      min: 5,
      max: 20,
      message: '用户密码长度必须介于 5 和 20 之间',
      trigger: 'blur',
    },
  ],
  email: [
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: ['blur', 'change'],
    },
  ],
  phonenumber: [
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur',
    },
  ],
  roleIds: [
    {
      required: true,
      message: '至少选择一个角色',
      trigger: 'change',
    },
  ],
  deptId: [
    {
      required: true,
      message: '请选择该用户所属部门',
      trigger: 'change',
    },
  ],
})

// 页面数据
const state = reactive({
  // 部门数据
  deptTreeData: [],
  // 角色数据
  roleOptionData: [],

  // 表单数据
  formData: {
    deptId: '',
    userName: '',
    nickName: '',
    password: '',
    phonenumber: '',
    email: '',
    sex: '0',
    status: '0',
    remark: '',
    postIds: [],
    roleIds: [],
    avatar: 'https://songzx0106.github.io/images/favicon.png',
  },
})

onMounted(() => {
  getDeptTreeData()
})

// 查询部门下拉菜单数据
const getDeptTreeData = () => {
  listDept().then((res) => {
    state.deptTreeData = handTree(res.data)
  })
}

// 构造树形结构
const handTree = (list) => {
  return list.reduce((prev, curr, i, arr) => {
    curr.children = arr.filter((item) => item.parentId === curr.deptId)
    if (curr.parentId === 0) {
      prev.push(curr)
    }
    return prev
  }, [])
}

// 确定按钮
const onConfirm = () => {
  console.log(state.formData)
  userEl.value.validate((valid, fields) => {
    if (valid) {
      if (state.formData.userId) {
        updateUser(state.formData).then((res) => {
          ElMessage.success('修改成功')
          emit('close', true)
        })
      } else {
        addUser(state.formData).then((res) => {
          ElMessage.success('新增成功')
          emit('close', true)
        })
      }
    }
  })
}

// 回填数据
const setFormData = (form, roleOptionsList) => {
  // 显示所有的角色列表
  state.roleOptionData = roleOptionsList
  state.formData = {
    deptId: '',
    userName: '',
    nickName: '',
    password: '',
    phonenumber: '',
    email: '',
    sex: '0',
    status: '0',
    remark: '',
    postIds: [],
    roleIds: [],
    avatar: 'https://songzx0106.github.io/images/favicon.png',
  }
  if (typeof form === 'object' && form !== null) {
    state.formData = Object.assign(state.formData, form)
  }
}

defineExpose({
  setFormData,
})
</script>

<style scoped lang="scss">
.tree-border {
  padding: 10px;
  width: 100%;
  border: 1px solid var(--el-color-primary);
  border-radius: 5px;
  min-height: 200px;
  max-height: 400px;
  overflow: auto;
}
</style>
